package org.bees.cms.common;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

public class Mappers {

	public static String getTableName(Class<?> mapper) throws Exception {
		Table table = mapper.getAnnotation(Table.class);
		String name = table == null ? null : table.name();
		return name == null || name.equals("") ? mapper.getSimpleName() : name;
	}

	public static String getColumnName(Class<?> mapper, String property) throws Exception {
		property = property.split("\\.")[0];
		PropertyDescriptor descriptor = new PropertyDescriptor(property, mapper);
		Method method = descriptor.getReadMethod();
		Column column = method.getAnnotation(Column.class);
		String name = column == null ? method.getReturnType().isAnnotationPresent(Entity.class) ? property + "_id" : property : column.name();
		return name == null || name.equals("") ? property : name;
	}
}
